import { autoUpdater } from "electron-updater";
import { dialog } from 'electron';
import log from 'electron-log';

export function setupAutoUpdater() {
    autoUpdater.autoDownload = false;

    autoUpdater.setFeedURL({
        provider: 'generic',
        url: 'https://gitee.com/glenngao/automation-tools-platform-update/raw/master/',
        disableWebInstaller: true,
    } as any);
    log.info(`当前更新源地址: ${autoUpdater.getFeedURL()}`);

    autoUpdater.on('checking-for-update', () => {
        log.info('Checking for updates...');
    });

    autoUpdater.on('update-available', () => {
        dialog.showMessageBox({
            type: 'info',
            title: '新版本可用',
            message: '有一个可用的新版本，正在更新...',
            buttons: ['确认']
        }).then(() => {
            autoUpdater.downloadUpdate();
        });
    });

    autoUpdater.on('update-not-available', () => {
        log.info('This is the latest version!');
    });

    autoUpdater.on('error', (err: any) => {
        log.error(`Update Error: ${err.message}`);
        if (err.message.includes('Cannot download differentially')) {
            log.warn('Fallback to full download...');
            autoUpdater.downloadUpdate(); // 强制重新下载完整更新
        } else {
            dialog.showErrorBox('更新失败', `更新过程中发生错误: ${err.message}`);
        }
    });

    autoUpdater.on('download-progress', (progressObj: any) => {
        log.info(`Downloading: ${progressObj.percent}%`);
    });

    autoUpdater.on('update-downloaded', () => {
        dialog.showMessageBox({
            type: 'info',
            title: '下载完成',
            message: '更新已准备就绪',
            buttons: ['退出并更新', '稍后']
        }).then(resp => {
            if (resp.response === 0) {
                autoUpdater.quitAndInstall(false, true);
            }
        });
    });
}

export function checkForUpdates() {
    autoUpdater.checkForUpdates().catch(err => { // 添加错误捕获
        log.error(`Update check failed: ${err.message}`);
        dialog.showErrorBox('更新检查失败', `无法连接更新服务器: ${err.message}`);
    });
}